import {Component, OnInit} from "@angular/core";
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {HttpClient} from "@angular/common/http";
import {AppUrl} from "../../../../app.url";

@Component({
    templateUrl:'passwordManage.component.html',
    styles:['passwordManage.component.less']
})

export class PasswordManageComponent implements OnInit{

    // oldPassword:string;
    // newPassword:string;
    // confirmP:string;

    infoType:string;
    info:string;
    notice:string;
    code:any;

    validateForm: FormGroup;
    submitForm=($event,value)=>{
        $event.preventDefault();
        for(const key in this.validateForm.controls){
            this.validateForm.controls[key].markAsDirty();
        }
        console.log(value);
        this.http.post(AppUrl.user.passwordUpdateUrl,{
            userid:localStorage.getItem('userid'),password:this.validateForm.controls['oldPassword'].value,
            newpassword:this.validateForm.controls['newPassword'].value
        }).subscribe(data=>{
            console.log(data);
            let temp:any=data;
            this.notice=temp.msg;
            this.code=temp.code;
        });
    }

    constructor(private fb: FormBuilder,private http:HttpClient){
        this.validateForm=this.fb.group({
            oldPassword:['',[Validators.required]],
            newPassword:['',[Validators.required,Validators.minLength(6),this.passwordCompare]],
            confirmP:['',[this.passwordConfirmationValidator]]
        });
    };

    ngOnInit(){}

    passwordConfirmationValidator=(control:FormControl):{ [s: string]: boolean }=>{
        if (!control.value) {
            return { required: true };
        } else if (control.value !== this.validateForm.controls[ 'newPassword' ].value) {
            return { confirm: true, error: true };
        }
    };

    passwordCompare=(control:FormControl): { [s: string]: boolean }=>{
        if (!control.value) {
            return { required: true };
        } else if (control.value == this.validateForm.controls[ 'oldPassword'].value) {
            return { confirm: true, error: true };
        }
    };

    save(){

    }

    getFormControl(name) {
        return this.validateForm.controls[name];
    }

    validateOldPassword(){
        setTimeout(_ => {
            this.validateForm.controls[ 'oldPassword' ].updateValueAndValidity();
        })
    }

    validateNewPassword(){
        setTimeout(_ => {
            this.validateForm.controls[ 'newPassword' ].updateValueAndValidity();
        })
    }

    afterClose(){
        this.notice=null;
        this.code=null;
    }
}
